package com.carefree.bookmall.service.impl;

import com.carefree.bookmall.common.utils.AesEncryptUtil;
import com.carefree.bookmall.common.vo.PageVO;
import com.carefree.bookmall.dao.RoleMapper;
import com.carefree.bookmall.dao.UserMapper;
import com.carefree.bookmall.entity.User;
import com.carefree.bookmall.exception.CustomException;
import com.carefree.bookmall.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * @ClassName:UserServiceImpl
 * @Description:
 * @Author Tengbin
 */
@Service(value = "userService")
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private RoleMapper roleMapper;


    /**
     * 注册用户
     *
     * @param user 用户信息
     * @return
     */
    @Override
    public boolean register(User user) throws Exception {
        // 查询当前注册的用户名是否已注册
        int rows = userMapper.identifyByUserName(user.getUserName());

        if (rows <= 0) {
            // 收货地址
            if (user.getAddress() == null) {
                user.setAddress("北京市");
            }
            // 密码
            if (user.getPassword().isEmpty()) {
                user.setPassword(AesEncryptUtil.getInstance().encrypt("123456"));
            } else {
                user.setPassword(user.getPassword());
            }

            // 真实姓名
            if (user.getRealName() == null) {
                user.setRealName("新用户" + user.getPhone());
            }
            if (user.getRoleId() == null) {
                // 配置默认角色
                user.setRoleId(2);
            }

            // 若当前的用户名没有注册，则添加
            int rows2 = userMapper.addUser(user);

            if (rows2 <= 0) {
                throw new CustomException("添加该用户失败，请检查后重试！");
            }
            // 为当前用户添加用户角色关联信息
            int rows3 = roleMapper.insertUserRole(user.getId(), user.getRoleId());
            if (rows3 <= 0) {
                throw new CustomException("添加该用户角色关联信息失败，请检查后重试！");
            }
            return true;
        }
        return false;
    }


    /**
     * 用户登录
     *
     * @param userName 用户名
     * @return
     * @throws CustomException
     */
    @Override
    public User login(String userName) throws CustomException {
        if (StringUtils.isBlank(userName)) {
            throw new CustomException("用户登录名必须不为空！");
        }
        // 根据用户名查询用户信息
        return userMapper.login(userName);
    }

    /**
     * 修改用户的手机号及地址
     *
     * @param userId  用户id
     * @param phone   用户手机号
     * @param address 用户地址
     * @return
     */
    @Override
    public boolean updatePhoneAndAddress(Integer userId, String realName, String phone, String address) throws CustomException {
        if (phone.isEmpty() || address.isEmpty() || userId == null) {
            throw new CustomException("修改个人信息的必要参数不能为空哦~");
        }
        return userMapper.updatePhoneAndAddressById(userId, realName, phone, address) > 0;
    }

    /**
     * 修改密码
     *
     * @param userId      用户id
     * @param password    新密码
     * @param oldpassword 旧密码
     * @return
     */
    @Override
    public boolean updatePassword(Integer userId, String oldUserPassword, String newUserPassword) throws Exception {

        if (oldUserPassword.isEmpty() || newUserPassword.isEmpty()) {
            throw new CustomException("新密码或旧密码不能为空！");
        }
        // 1.查询用户当前密码并解密
        String tempUpwd = AesEncryptUtil.getInstance().desEncrypt(userMapper.selectUserPasswordById(userId));

        // 3.比较查询的密码和客户端输入的密码
        if (tempUpwd.equals(oldUserPassword)) {
            // 5.返回执行结果
            return userMapper.updatePassword(userId, newUserPassword) > 0;
        }
        return false;
    }

    /**
     * 更新密码
     *
     * @param userId   用户id
     * @param password 密码
     * @return
     */
    @Override
    public boolean updatePassword(Integer userId, String password) throws Exception {
        if (password.isEmpty()) {
            throw new IllegalArgumentException("需修改的密码不能为空！");
        }
        return userMapper.updatePassword(userId, password) > 0;
    }

    /**
     * 分页查询用户信息
     *
     * @param pageNumber
     * @return
     */
    @Override
    public PageVO queryUser(int pageNumber, int pageSize) {
        if (pageNumber <= 0) {
            pageNumber = 1;
        }
        // 实例化分页对象
        PageVO pageVO = new PageVO();
        // 每页显示记录数
        int totalCount = userMapper.selectCountOfUser();
        List<User> users = userMapper.selectUser((pageNumber - 1) * pageSize, pageSize);

        // 为属性赋值
        pageVO.setPageNumber(pageNumber);
        pageVO.SetPageSizeAndTotalCount(pageSize, totalCount);
        pageVO.setList((List) users);

        return pageVO;
    }

    /**
     * 删除用户
     *
     * @param userId 用户id
     * @return
     */
    @Override
    public boolean deleteUser(Integer userId) throws CustomException {
        if (userId <= 0 || userId == null) {
            throw new CustomException("未获取到用户主键信息！");
        }
        return userMapper.deleteUserById(userId) > 0;
    }

    /**
     * 根据用户id查询用户信息
     *
     * @param userId
     * @return
     */
    @Override
    public User queryUserByUserId(Integer userId) throws CustomException {
        if (userId <= 0) {
            throw new CustomException("无效用户信息！");
        }
        return userMapper.selectUserById(userId);
    }

    /**
     * 修改部分用户信息
     *
     * @param user 需修改的用户对象
     * @return
     */
    @Override
    public boolean updateUserSeletive(User user) throws CustomException {
        if (ObjectUtils.isEmpty(user)) {
            throw new CustomException("未获取到用户的信息！");
        }
        return userMapper.updateUserSeletive(user) > 0;
    }


    /**
     * 查询当天新增的用户
     *
     * @return
     */
    @Override
    public int queryTodayUserCount() {
        return userMapper.selectTodayUserCount();
    }


    /**
     * 查询用户总数
     *
     * @return
     */
    @Override
    public int queryUserCounts() {
        return userMapper.selectCountOfUser();
    }

}
